<template>
  <div class="user-edit-container">
    <el-card class="edit-card">
      <h2 class="form-title">编辑用户</h2>
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="user-form">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" multiple placeholder="请选择角色" style="width: 100%;">
            <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button type="primary" @click="submitForm('form')" icon="el-icon-check">保存</el-button>
          <el-button @click="cancel" icon="el-icon-back">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserById, updateUser } from '@/api/user'
import { getRoleListAll } from '@/api/role'

export default {
  data() {
    return {
      form: {
        id: '',
        username: '',
        password: '',
        roleId: []
      },
      rules: {
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      roles: []
    }
  },
  created() {
    this.fetchUser()
    this.fetchRoles()
  },
  methods: {
    async fetchUser() {
      try {
        const userId = this.$route.params.id
        if (!userId) {
          throw new Error('未获取到用户ID')
        }
        const response = await getUserById(userId)
        const userData = response.data.data
        this.form = {
          id: userData.id,
          username: userData.username,
          password: '',
          roleId: userData.userRoleList.map(role => role.roleId)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败：' + error.message)
        this.$router.push('/users')
      }
    },
    async fetchRoles() {
      try {
        const response = await getRoleListAll()
        this.roles = response.data.data
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            await updateUser(this.form)
            this.$message.success('更新用户成功')
            this.$router.push('/users')
          } catch (error) {
            console.error('更新用户失败:', error)
            this.$message.error('更新用户失败')
          }
        }
      })
    },
    cancel() {
      this.$router.push('/users')
    }
  }
}
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
}

.edit-card {
  margin-bottom: 20px;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
  font-size: 24px;
  font-weight: 600;
}

.user-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}

.form-buttons {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.form-buttons .el-button {
  margin: 0 10px;
  padding: 12px 24px;
  font-size: 14px;
}
</style>